<template>
  <div>
    <el-breadcrumb style="margin-bottom: 20px;" :separator-icon="ArrowRight">
      <el-breadcrumb-item :to="{ path: '/OrderInfo' }">订单信息管理</el-breadcrumb-item>
      <el-breadcrumb-item>{{ '订单详细' }}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-descriptions title="订单信息">
      <el-descriptions-item label="订单id：">{{ orderinfo.orderId }}</el-descriptions-item>
      <el-descriptions-item label="创建时间：">{{ GetDateTime(orderinfo.creationTime) }}</el-descriptions-item>
      <el-descriptions-item label="客户：">{{ orderinfo.customerName }}</el-descriptions-item>
      <el-descriptions-item label="完成状态：">{{ orderinfo.state == '0' ? '未完成' : '完成' }}</el-descriptions-item>
      <el-descriptions-item label="描述：">
        {{ orderinfo.description }}
      </el-descriptions-item>
    </el-descriptions>
    <div>
      <span style="display: flex; width: 100%;">
        <el-button type="primary"
          @click="cleanform(fromRuleRef), dialogFormVisible = true, dialog_title = '新增订单项'">新增</el-button>
        <el-button type="danger" @click="DelList">批量删除</el-button>
        <el-input v-model="query" type="number" style="max-width: 400px;margin-left: 10px;" placeholder="Please input"
          class="input-with-select">
          <template #prepend>
            <el-select v-model="select" placeholder="订单项编号" style="width: 115px">
              <el-option v-for="item in ['产品编号', '订单项编号']" :key="item.indexOf" :label="item" :value="item" />
            </el-select>
          </template>
          <template #append>
            <el-button :icon="Search" @click="selectbut" />
          </template>
        </el-input>
        <el-radio-group @change="changeRadio" v-model="radio" style="margin-left: 10px;">
          <el-radio :value="-1">全部</el-radio>
          <el-radio :value="0">未完成</el-radio>
          <el-radio :value="1">完成</el-radio>
        </el-radio-group>
      </span>
      <el-table style="margin-top:10px;" border :data="tableData" max-height="80vh" width="100vw"
        @selection-change="handleSelectionChange">
        <el-table-column fixed type="selection" width="45" />
        <el-table-column fixed prop="orderItemId" label="订单项编号" width="120" />
        <el-table-column prop="productId" label="产品编号" width="120" />
        <el-table-column prop="state" label="状态" width="120">
          <template #default="scope">
            {{ scope.row.state == '0' ? '未完成' : '完成' }}
          </template>
        </el-table-column>
        <el-table-column prop="num" label="数量" width="120" />
        <el-table-column fixed="right" label="Operations" width="120">
          <template #default="scope">
            <el-popconfirm title="确认删除这条信息？" confirm-button-text="是的" cancel-button-text="不要"
              @confirm="Del(scope.$index)">
              <template #reference>
                <el-button link type="primary" size="small">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
            <el-button link type="primary" size="small"
              @click="Updata(scope.$index), dialog_title = '修改订单项'">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="width: 100%; margin-top: 10px;">
        <el-pagination style="margin: auto; width: 600px;" v-model:current-page="currentPage"
          v-model:page-size="pageSize" :page-sizes="[5, 10, 50, 100, 200, 300, 400]" :small="small" :disabled="disabled"
          :background="background" layout="total, sizes, prev, pager, next, jumper" :total="totalCount"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
      <el-dialog v-model="dialogFormVisible" :title="dialog_title" width="600">
        <el-form :model="form" :rules="rules" ref="fromRuleRef">
          <el-form-item label="产品编号" :label-width="120" prop="name">
            <el-input v-model="form.productId" placeholder="请输入产品编号" autocomplete="off" />
          </el-form-item>
          <el-form-item label="数量" :label-width="120" prop="num">
            <el-input v-model="form.num" placeholder="请输入数量" type="number" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cleanform(fromRuleRef)">取消</el-button>
            <el-button type="primary" @click="Add(fromRuleRef)">
              确认
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>

  </div>
</template>

<script setup lang="ts">

import { GetDateTime } from "../../utils/storage"
import { ArrowRight } from '@element-plus/icons-vue'
import { onBeforeMount, onBeforeUnmount, onBeforeUpdate, onMounted, onUnmounted, onUpdated, ref, reactive } from 'vue';
import { Search } from '@element-plus/icons-vue'
import { getAllOrderItem, addOrderItem, updateOrderItem, removeOrderItem, removeOrderItems } from "../../request/apis/OrderItemApi";
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from "vue-router";
import type { FormInstance, FormRules } from "element-plus";
const route = useRoute()
onBeforeMount(() => {
  let obj = JSON.parse(route.query.obj + "")
  orderinfo.orderId = obj.orderId
  orderinfo.creationTime = obj.creationTime
  orderinfo.state = obj.state
  orderinfo.customerName = obj.customerName
  orderinfo.description = obj.description
  updateData()
})
const orderinfo = reactive({
  orderId: 0,
  creationTime: "",
  state: "",
  customerName: "",
  description: ""
})
const form = reactive({
  orderItemId: "",
  productId: "",
  orderId: 0,
  state: "",
  num: 0
})
const fromRuleRef = ref<FormInstance>()
const rules = reactive<FormRules>({
  name: [{ required: true, message: "请输入产品编号", trigger: "blur" }]
})
const tableData = ref([])
const query = ref("")
const dialogFormVisible = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const select = ref("")
const radio = ref(-1)

const cleanform = async (ruleFrom: FormInstance | undefined) => {
  dialogFormVisible.value = false
  iupdate = false
  form.orderItemId = ""
  form.productId = ""
  form.orderId = orderinfo.orderId
  form.state = ""
  form.num = 0
  if (!ruleFrom) return
  ruleFrom.resetFields()
}

const selectbut = () => {//查询
  updateData()
}
const changeRadio = () => {//查询
  updateData()
}


let dellist: [] = []
const handleSelectionChange = (val: []) => {//选择框变化
  dellist = val
  console.log(val)
}
const updateData = () => {//刷新数据
  let id1 = -1, id2 = -1
  if (query.value != '') {
    if (select.value.endsWith("产品编号")) {
      id1 = Number.parseInt(query.value)
    } else {
      id2 = Number.parseInt(query.value)
    }
  }
  getAllOrderItem(pageSize.value, currentPage.value, orderinfo.orderId, id1, id2,radio.value).then((res) => {
    if (res.data == null) return
    tableData.value = res.data.list
    currentPage.value = res.data.currPage
    totalCount.value = res.data.totalCount
  })
}
const Del = (id: number) => {//删除
  removeOrderItem(tableData.value[id].orderItemId).then(res => {
    if (res.code == 200) {
      ElMessage({
        message: '修改成功',
        type: 'success',
      })
    } else {
      ElMessage.error(res.message)
    }
    updateData()
    cleanform(undefined)
  })
}
let iupdate = false
const Updata = (id: number) => {
  let obj = tableData.value[id]
  form.productId = obj.productId
  form.orderItemId = obj.orderItemId
  form.orderId = orderinfo.orderId
  form.state = obj.state
  form.num = obj.num
  dialogFormVisible.value = true
  iupdate = true
  console.log(iupdate)
}
const DelList = () => {//批量删除
  let ids:[] = dellist.map(person => person.orderItemId)
  if (ids.length == 0) return
  removeOrderItems(ids).then((res => {
    if (res.code == 200) {
      ElMessage({
        message: '删除成功',
        type: 'success',
      })
    } else {
      ElMessage.error(res.message)
    }
    updateData()
  }))
}
const Add = async (ruleFrom: FormInstance | undefined) => {
  if (!ruleFrom) return;
  await ruleFrom.validate((valid, fields) => {
    if (valid) {
      dialogFormVisible.value = false
      if (iupdate) {
        console.log(iupdate)
        updateOrderItem(form).then(res => {
          if (res.code == 200) {
            ElMessage({
              message: '删除成功',
              type: 'success',
            })
          } else {
            ElMessage.error(res.message)
          }
          updateData()
          iupdate = false
        })
      } else {
        addOrderItem(form).then(res => {
          if (res.code == 200) {
            ElMessage({
              message: '添加成功',
              type: 'success',
            })
          } else {
            ElMessage.error(res.message)
          }
          updateData()
        })
      }
    } else {
      return;
    }
  });
}
const handleSizeChange = (val: number) => {
  updateData()
}
const handleCurrentChange = (val: number) => {
  updateData()
}

</script>

<style></style>